dojo.require("dojox.cometd");
var cometd = dojox.cometd;
var connection = {};

var EC = {
	REST_Path: '',
	instanceName: '',
	subscription: null,
	alertSubscription: null,
	registered: false,
	clientID: '',
	UI: {},
	init: function(conf) {
		this.REST_Path = conf.hostUrl + "synchronizer/event";
		this.instanceName = conf.key;
		this.subscription = null;
		this.clientID = EC.randomString();
		
		this.UI = {
			btnRegister: dojo.query(conf.register)[0],
			btnUnregister: dojo.query(conf.unregister)[0],
			registrationStatus: dojo.query(conf.registrationStatus)[0],
			statusBar: dojo.query(conf.status)[0],
			eventTime: dojo.query(conf.eventTime)[0],
			usersMissing: dojo.query(conf.usersMissing)[0],
			placesAvailable: dojo.query(conf.placesAvailable)[0],
			alertTime: dojo.query(conf.alertTime)[0],
			btnAddAlert: dojo.query(conf.btnAddAlert)[0],
			alertStatus: dojo.query(conf.alertStatus)[0]
		}
		
		// initialise UI
		this.UI.btnRegister.onclick = function(e){
			EC.registerToEvent();
		};
		this.UI.btnUnregister.onclick = function(e){
			EC.unregisterFromEvent();
		};
		this.UI.btnAddAlert.onclick = function(e){
			EC.addAlert();
		};
		this.UI.btnUnregister.disabled = true;
	},
	
	doSubscribe: function() {
		if (this.subscription) {
			cometd.unsubscribe(this.subscription);
		}
		this.subscription = cometd.subscribe(this.instanceName, EC.onPublish);
		return;
	},
	
	doUnsubscribe: function() {
		if (this.subscription) {
			cometd.unsubscribe(this.subscription);
		}
		return;
	},
	
	onPublish: function(message){
		var update = message.data;
		if(update.error){
			EC.UI.statusBar.innerHTML = update.error;
			return;
		}
		if (update == null) return;
		EC.updateUI(update);
	},
	
	onResponse: function(data){
		if (data.indexOf("Failed") == 0 || data.indexOf("Exception") == 0) {
			EC.UI.statusBar.innerHTML = data;
			return;
		}
		var update = eval('(' + data + ')');
		if (update == null) return;
		EC.updateUI(update);
	},
	
	updateUI: function(update){
		if (update.description == "eventStart"){
			EC.onEventStart(update);
		} else if (update.description == "alertUser"){
			EC.alertUser(update.user);
		} else if (update.description == "getInfo") {
			EC.updateRegistration(update);
		}
	},
	
	onEventStart: function(update){
		EC.UI.btnRegister.disabled = true;
		EC.UI.btnUnregister.disabled = true;
		if(update.eventStarting){
			EC.UI.statusBar.innerHTML = "Prijave su završene, događaj će se održati.";
		} else {
			EC.UI.statusBar.innerHTML = "Prijave su završene, događaj je otkazan.";
		}
		EC.doUnsubscribe();
	},
	
	updateRegistration: function(update){
		// show time
		if(!!update.eventTime) EC.UI.eventTime.innerHTML = update.eventTime;
		
		var usersMissing = ( update.minParticipants - update.usersCount );
		usersMissing = (usersMissing > 0) ? usersMissing : 0;
		var placesAvailable = ( update.maxParticipants - update.usersCount );
	
		// show nubers
		EC.UI.usersMissing.innerHTML = '' + usersMissing;
		EC.UI.placesAvailable.innerHTML = '' + placesAvailable;
		
		// disable registration if no places available
		if (!EC.registered){
			if(placesAvailable == 0){
				EC.UI.btnRegister.disabled = true;
			} else {
				EC.UI.btnRegister.disabled = false;
			}
		}		
	},
	
	alertUser: function(user){
		alert("Vaš podsjetnik.");
	},
	
	registerToEvent: function() {
		if (this.instanceName == '')
			return "Failed: No Event set.";
		var xhrArgs = {
			url: this.REST_Path,
			handleAs: "json",
			preventCache: true,
			content: {
				"mechanism": "event",
				"operation": "register",
				"name": EC.instanceName,
				"user": EC.clientID
			},
			load: function(data) {
				if (data.isRegistered){
					EC.registered = true;
					EC.UI.registrationStatus.innerHTML = "Prijavljeni ste";
					EC.UI.btnRegister.disabled = true;
					EC.UI.btnUnregister.disabled = false;
				}
				return;	
			},
			error: function(error) {
				EC.UI.statusBar.innerHTML = "An unexpected error occurred: " + error;
			}
		}
		//Call the asynchronous xhrGet
		var deferred = dojo.xhrPost(xhrArgs);
		return;
	},
	
	unregisterFromEvent: function() {
		if (this.instanceName == '')
			return "Failed: No Event set.";
		var xhrArgs = {
			url: this.REST_Path,
			handleAs: "json",
			preventCache: true,
			content: {
				"mechanism": "event",
				"operation": "unregister",
				"name": this.instanceName,
				"user": EC.clientID
			},
			load: function(data) {
				if (!data.isRegistered){
					EC.registered = false;
					EC.UI.registrationStatus.innerHTML = "Odjavljeni ste";
					EC.UI.btnRegister.disabled = false;
					EC.UI.btnUnregister.disabled = true;
				}
				return;	
			},
			error: function(error) {
				EC.UI.statusBar.innerHTML = "An unexpected error occurred: " + error;
			}
		}
		//Call the asynchronous xhrGet
		var deferred = dojo.xhrPost(xhrArgs);
		return;
	},
	
	getInfo: function() {
		if (this.instanceName == '')
			return "Failed: No Event set.";
		var xhrArgs = {
			url: this.REST_Path,
			handleAs: "text",
			preventCache: true,
			content: {
				"mechanism": "event",
				"operation": "getinfo",
				"name": this.instanceName,
				"user": EC.clientID
			},
			load: function(data) {
				EC.onResponse(data);
				return;	
			},
			error: function(error) {
				EC.UI.statusBar.innerHTML = "An unexpected error occurred: " + error;
			}
		}
		//Call the asynchronous xhrGet
		var deferred = dojo.xhrPost(xhrArgs);
		return;
	},
	
	addAlert: function() {
		if (this.instanceName == '')
			return "Failed: No Event set.";
		var xhrArgs = {
			url: this.REST_Path,
			handleAs: "json",
			preventCache: true,
			content: {
				"mechanism": "event",
				"operation": "addalert",
				"name": EC.instanceName,
				"user": EC.clientID,
				"alertTime": EC.UI.alertTime.value
			},
			load: function(data) {
				if(data.isAlertAdded){
					// subscribe to channel
					var alertChannel = EC.instanceName + "/" + EC.clientID;
					if (EC.alertSubscription) {
						cometd.unsubscribe(EC.alertSubscription);
					}
					EC.alertSubscription = cometd.subscribe(alertChannel, EC.onPublish);
				
					// update interface
					var selectedIndex = EC.UI.alertTime.selectedIndex;
					var alertLabel =  EC.UI.alertTime.options[ selectedIndex ].text;
					EC.UI.alertStatus.innerHTML = EC.UI.alertStatus.innerHTML+"<br />" + alertLabel;
				}
				return;
			},
			error: function(error) {
				EC.UI.statusBar.innerHTML = "An unexpected error occurred: " + error;
			}
		}
		//Call the asynchronous xhrGet
		var deferred = dojo.xhrPost(xhrArgs);
		return;
	},
	
	randomString: function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 12;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	},
	
};
